<template>
  <div>
    <el-button icon="el-icon-download" size="mini" :loading="generating" @click="handleShowDownload">
      导出数据
    </el-button>
    <el-dialog title="数据下载" :visible.sync="showDownload" append-to-body width="60%">
      <el-tabs v-model="activeTab" class="download-tabs">
        <el-tab-pane label="下载设置" name="downloadSettings">
          <el-form :model="downloadTemp" label-width="120px" class="download-form">
            <el-form-item label="选择下载字段">
              <el-checkbox-group v-model="downloadTemp.fields">
                <el-checkbox v-for="field in availableFields" :key="field.value" :label="field.value">
                  {{ field.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item v-for="(value, key) in filters" :key="key" :label="key">
              <template v-if="isIdField(key)">
                <el-input v-model="downloadTemp.filters[key]" :disabled="true" style="width: 200px;" />
              </template>
              <template v-else-if="isBooleanFilter(key, downloadTemp.filters[key])">
                <el-switch v-model="downloadTemp.filters[key]" />
              </template>
              <template v-else-if="isRangeFilter(key)">
                <el-input-number v-model="downloadTemp.filters[key]" style="width: 200px;" />
              </template>
              <template v-else>
                <el-input v-model="downloadTemp.filters[key]" style="width: 200px;" />
              </template>
            </el-form-item>
            <el-form-item label="下载数量">
              <el-input-number
                v-model="downloadTemp.total"
                :min="0"
                :placeholder="'0 表示下载所有数据'"
                style="width: 200px;"
              />
              <span style="margin-left: 10px; color: #909399; font-size: 14px;">0 表示下载所有数据</span>
            </el-form-item>
            <el-form-item label="关键词过滤">
              <el-input v-model="downloadTemp.kw" style="width: 200px;" />
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="下载历史" name="downloadHistory">
          <el-card v-if="downloadHistory.length" class="download-history">
            <div slot="header">
              <span>下载历史</span>
              <el-button style="float: right; padding: 3px 0" type="text" @click="clearHistory">清空历史</el-button>
            </div>
            <el-table :data="downloadHistory" style="width: 100%">
              <el-table-column prop="timestamp" label="生成时间" width="180">
                <template slot-scope="scope">
                  {{ formatDate(scope.row.timestamp) }}
                </template>
              </el-table-column>
              <el-table-column prop="url" label="下载链接">
                <template slot-scope="scope">
                  <el-link :href="scope.row.url" target="_blank">下载文件</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
          <div v-else>暂无下载历史</div>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button @click="showDownload = false">取 消</el-button>
        <el-button type="primary" :loading="generating" @click="downloadFile">生 成</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { GenerateExcel } from '@/api/crm/generate_excel'

export default {
  name: 'Crmdownloador',
  props: {
    tableName: {
      type: String,
      required: true
    },
    fields: {
      type: Array,
      default: () => []
    },
    filters: {
      type: Object,
      default: () => ({})
    },
    availableFields: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      showDownload: false,
      generating: false,
      download_url: '',
      downloadTemp: {
        table_name: this.tableName,
        fields: this.fields,
        kw: '',
        filters: {},
        total: 0,
        order_by: '',
        order_desc: 0
      },
      downloadHistory: [],
      activeTab: 'downloadSettings'
    }
  },
  watch: {
    filters: {
      handler(newFilters) {
        this.updateFilters(newFilters)
      },
      deep: true
    }
  },
  created() {
    this.initFilters()
    this.updateFilters(this.filters)
  },
  methods: {
    updateFilters(newFilters) {
      // 清空现有的 filters
      this.downloadTemp.filters = {}
      // 使用新的 filters 更新 downloadTemp.filters
      for (const [key, value] of Object.entries(newFilters)) {
        this.$set(this.downloadTemp.filters, key, value)
      }
    },
    initFilters() {
      for (const [key, value] of Object.entries(this.filters)) {
        this.$set(this.downloadTemp.filters, key, value)
      }
    },
    handleShowDownload() {
      this.showDownload = true
      this.loadDownloadHistory()
    },
    isRangeFilter(key) {
      return key.endsWith('__gte') || key.endsWith('__lte')
    },
    isBooleanFilter(key, value) {
      return typeof value === 'boolean'
    },
    isIdField(key) {
      return key.endsWith('_id')
    },
    downloadFile() {
      this.generating = true
      const processedFilters = this.processFilters(this.downloadTemp.filters)
      const downloadData = {
        ...this.downloadTemp,
        filters: processedFilters
      }
      if (downloadData.total === 0) {
        downloadData.pagesize = 1000000 // 使用一个很大的数字来表示"所有"
      } else {
        downloadData.pagesize = downloadData.total
      }
      delete downloadData.total // 删除 total 字段，因为后端不需要

      GenerateExcel(downloadData)
        .then(response => {
          this.download_url = response.download_url
          this.addToDownloadHistory(this.download_url)
          window.open(response.download_url)
          this.generating = false
          this.$emit('download-success', this.download_url)
        })
        .catch(err => {
          console.error(err)
          this.generating = false
          this.$emit('download-error', err)
        })
    },
    processFilters(filters) {
      const processedFilters = {}
      for (const [key, value] of Object.entries(filters)) {
        if (value !== null && value !== undefined && value !== '') {
          processedFilters[key] = value
        }
      }
      return processedFilters
    },
    addToDownloadHistory(url) {
      const newEntry = {
        timestamp: new Date().getTime(),
        url: url
      }
      this.downloadHistory.unshift(newEntry)
      if (this.downloadHistory.length > 10) {
        this.downloadHistory.pop()
      }
      this.saveDownloadHistory()
    },
    loadDownloadHistory() {
      const savedHistory = localStorage.getItem(`downloadHistory_${this.tableName}`)
      if (savedHistory) {
        this.downloadHistory = JSON.parse(savedHistory)
      }
    },
    saveDownloadHistory() {
      localStorage.setItem(`downloadHistory_${this.tableName}`, JSON.stringify(this.downloadHistory))
    },
    clearHistory() {
      this.downloadHistory = []
      localStorage.removeItem(`downloadHistory_${this.tableName}`)
    },
    formatDate(timestamp) {
      const date = new Date(timestamp)
      return date.toLocaleString()
    }
  }
}
</script>

<style scoped>
.download-history {
  margin-top: 20px;
}
.el-dialog {
  min-width: 600px;
}
.download-tabs ::v-deep .el-tabs__content {
  padding-top: 20px;
}
.download-form {
  padding-top: 10px;
}
</style>
